// 初始化数据库
const sequelize = require('./dbConnect'); // 数据库连接实例
const adminModel = require('../model/adminModel');// 管理员模型
const bannerModel = require('../model/bannerModel');
const md5 = require("md5");
const blogTypeModel = require("../model/blogTypeModel");
const blogModel = require('../model/blogModel');
const messageModel = require('../model/messageModel');
const userModel = require('../model/userModel');
const returnSchoolModel = require('../model/returnSchoolModel');
const askModel = require('../model/askModel');

(async function () {
    // 定义模型之间的关联关系

    // 文章与文章分类之间的关联
    blogTypeModel.hasMany(blogModel, {foreignKey: 'categoryId', targetKey: 'id'})
    blogModel.belongsTo(blogTypeModel, {foreignKey: 'categoryId', targetKey: 'id', as: 'category'})
    // 文章和评论之间的关联
    blogModel.hasMany(messageModel, {foreignKey: 'blogId', targetKey: 'id'})
    messageModel.belongsTo(blogModel, {foreignKey: 'blogId', targetKey: 'id', as: 'blog'})
    // 返回学校表与用户表之间的关联
    userModel.hasOne(returnSchoolModel, { foreignKey: 'userId', targetKey: 'id' })
    returnSchoolModel.belongsTo(userModel, { foreignKey: 'userId', targetKey: 'id', as: 'user' })
    // 咨询表与用户表之间的关联
    userModel.hasMany(askModel, { as: 'askQuestions', foreignKey: 'askUserId' });
    userModel.hasMany(askModel, { as: 'replyQuestions', foreignKey: 'replyUserId' });
    askModel.belongsTo(userModel, { as: 'askUser', foreignKey: 'askUserId' });
    askModel.belongsTo(userModel, { as: 'replyUser', foreignKey: 'replyUserId' });

    // 同步模型和数据表
    await sequelize.sync({
        alter: true
    })
    // 如果没有数据，则初始化管理员数据
    const adminCount = await adminModel.count()
    if (!adminCount) {
        await adminModel.create({
            loginId: 'admin',
            name: '超级管理员',
            loginPwd: md5('123456'),
        })
        console.log('初始化管理员数据成功')
    }
    // banner 初始化操作
    const bannerCount = await bannerModel.count()
    if (!bannerCount) {
        await bannerModel.bulkCreate([{
            "midImg": "/static/images/bg1_mid.jpg",
            "bigImg": "/static/images/bg1_big.jpg",
            "title": "塞尔达旷野之息",
            "description": "2017年年度游戏，期待续作"
        }, {
            "midImg": "/static/images/bg2_mid.jpg",
            "bigImg": "/static/images/bg2_big.jpg",
            "title": "塞尔达四英杰",
            "description": "四英杰里面你最喜欢的又是谁呢"
        }, {
            "midImg": "/static/images/bg3_mid.jpg",
            "bigImg": "/static/images/bg3_big.jpeg",
            "title": "日本街道",
            "description": "动漫中经常出现的日本农村街道，一份独特的恬静"
        }])
        console.log('初始化首页标语数据成功')
    }
    console.log('数据库初始化完成')
})()